import mysql.connector.pooling
import json

def _initialize_pool():
    config_path = './configs/config.json'
    try:
        with open(config_path, mode='r', encoding='utf-8') as f:
            config = json.load(f)
            db_config = config['mysql']
            Database._pool = mysql.connector.pooling.MySQLConnectionPool(
                pool_name="mysql_pool",
                pool_size=5,
                use_pure=True,
                **db_config
            )
    except FileNotFoundError:
        raise Exception("[mysql] 初始化失败 配置文件 config.json 未找到")
    except json.JSONDecodeError:
        raise Exception("[mysql] 初始化失败 配置文件格式错误")
    except KeyError:
        raise Exception("[mysql] 配置文件中缺少 database 部分")
    except mysql.connector.Error as err:
        raise Exception(f"[mysql] 连接池初始化失败: {err}")


class Database:
    _pool = None

    def __init__(self):
        if Database._pool is None:
            _initialize_pool()
        self.connection = None

    @property
    def pool(self):
        return Database._pool

    def __enter__(self):
        self.connection = Database._pool.get_connection()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.connection and self.connection.is_connected():
            self.connection.close()

    def query(self, query, params=None, fetch_one=False):
        try:
            with self.connection.cursor(dictionary=True) as cursor:
                cursor.execute(query, params or ())
                return cursor.fetchone() if fetch_one else cursor.fetchall()
        except mysql.connector.Error as err:
            print(f"[mysql] 查询失败:{err}")
            raise

    def dml(self, query, params=None):
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(query, params or ())
                self.connection.commit()
                return cursor.rowcount
        except mysql.connector.Error as err:
            self.connection.rollback()
            print(f"[mysql] dml失败:{err}")
            raise